# Copyright 2019 The Chromium Authors
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""Implements the interface of the results_processor module.

Provides functions to parse command line arguments and process options.
"""

import argparse
import datetime
import logging
import os
import re
import sys

from py_utils import cloud_storage

from core.results_processor import formatters
from core.results_processor import util


def ArgumentParser(standalone=False):
  """Create an ArgumentParser defining options required by the processor."""
  all_output_formats = list(formatters.FORMATTERS.keys())
  if not standalone:
    all_output_formats.append('none')
  parser, group = _CreateTopLevelParser(standalone)
  parser.add_argument(
      '-v', '--verbose', action='count', dest='verbosity', default=0,
      help='Increase verbosity level (repeat as needed)')
  group.add_argument(
      '--output-format', action='append', dest='output_formats',
      metavar='FORMAT', choices=all_output_formats, required=standalone,
      help=Sentences(
          'Output format to produce.',
          'May be used multiple times to produce multiple outputs.',
          'Avaliable formats: %(choices)s.',
          '' if standalone else 'Defaults to: html.'))
  group.add_argument(
      '--intermediate-dir', metavar='DIR_PATH', required=standalone,
      help=Sentences(
          'Path to a directory where intermediate results are stored.',
          '' if standalone else 'If not provided, the default is to create a '
          'new directory within "{output_dir}/artifacts/".'))
  group.add_argument(
      '--output-dir', default=_DefaultOutputDir(), metavar='DIR_PATH',
      help=Sentences(
          'Path to a directory where to write final results.',
          'Default: %(default)s.'))
  group.add_argument(
      '--max-values-per-test-case', type=int, metavar='NUM',
      help=Sentences(
          'Fail a test run if it produces more than this number of values.'
          'This includes both ad hoc and metric generated measurements.'))
  group.add_argument(
      '--reset-results', action='store_true',
      help=Sentences(
          'Overwrite any previous output files in the output directory.',
          'The default is to append to existing results.'))
  group.add_argument(
      '--results-label', metavar='LABEL',
      help='Label to identify the results generated by this run.')
  group.add_argument(
      '--test-path-format', metavar='FORMAT',
      choices=[util.TELEMETRY_TEST_PATH_FORMAT, util.GTEST_TEST_PATH_FORMAT],
      default=util.TELEMETRY_TEST_PATH_FORMAT,
      help=Sentences(
          'How to interpret the testPath attribute.',
          'Available options: %(choices)s. Default: %(default)s.'))
  group.add_argument(
      '--trace-processor-path',
      help=Sentences('Path to trace processor shell.',
                     'Default: download a pre-built version from the cloud.'))
  group.add_argument(
      '--upload-results', action='store_true',
      help='Upload generated artifacts to cloud storage.')
  group.add_argument(
      '--upload-bucket', default='output', metavar='BUCKET',
      help=Sentences(
          'Storage bucket to use for uploading artifacts.',
          'Supported values are: %s; or a valid cloud storage bucket name.'
          % ', '.join(sorted(cloud_storage.BUCKET_ALIASES)),
          'Defaults to: %(default)s.'))
  group.add_argument(
      '--experimental-tbmv3-metrics', action='store_true',
      help='Enable running experimental TBMv3 metrics.')
  group.add_argument(
      '--fetch-power-profile',
      action='store_true',
      help=('Specify this if you want to run proxy power metrics that use '
            'device power profiles.'))
  group.add_argument(
      '--extra-metric', action='append', dest='extra_metrics', metavar='METRIC',
      help=('Compute an extra metric on the test results. Metric should have '
            'the form "version:name", e.g. "tbmv3:power_rails_metric". '
            'Can be used multiple times.'))
  group.add_argument(
      '--is-unittest',
      action='store_true',
      help='Is running inside a unittest.')

  # Separate group for fetching device data
  device_group = parser.add_argument_group(title='Device fetching options')
  device_group.add_argument(
      '--fetch-device-data',
      action='store_true',
      help=('Argument to enable fetching data from a device.'))
  device_group.add_argument(
      '--fetch-device-data-platform',
      dest='fetch_data_platform',
      choices=['android', 'chromeos'],
      help='Platform associated with device type to pull data from. Only '
      'supports --fetch-device-data.')
  device_group.add_argument(
      '--fetch-data-path-device',
      dest='device_data_path',
      help=('Use this to specify the path on device to pull data from. Should '
            'be used with --fetch-device-data.'))
  device_group.add_argument(
      '--fetch-data-path-local',
      dest='local_data_path',
      default=os.environ.get('ISOLATED_OUTDIR', os.getcwd()),
      help=('Use this to override the local copy path. Defaults to '
            'ISOLATED_OUTDIR environment variable or cwd if ISOLATED_OUTDIR is '
            'not set. To be used in conjuction with --fetch-device-data.'))
  return parser


def ProcessOptions(options):
  """Adjust result processing options as needed before running benchmarks.

  Note: The intended scope of this function is limited to only adjust options
  defined by the ArgumentParser above. One should not attempt to read or modify
  any other attributes that the options object may have.

  Currently the main job of this function is to tease out and separate output
  formats to be handled by the results processor, from those that should fall
  back to the legacy output formatters in Telemetry.

  Args:
    options: An options object with values parsed from the command line.
  """
  if options.verbosity >= 2:
    logging.getLogger().setLevel(logging.DEBUG)
  elif options.verbosity == 1:
    logging.getLogger().setLevel(logging.INFO)
  else:
    logging.getLogger().setLevel(logging.WARNING)

  # The output_dir option is None or missing if the selected Telemetry command
  # does not involve output generation, e.g. "run_benchmark list", and the
  # argument parser defined above was not invoked.
  if getattr(options, 'output_dir', None) is None:
    return

  def resolve_dir(path):
    return os.path.realpath(os.path.expanduser(path))

  options.output_dir = resolve_dir(options.output_dir)

  if options.intermediate_dir:
    options.intermediate_dir = resolve_dir(options.intermediate_dir)
  else:
    if options.results_label:
      filesafe_label = re.sub(r'\W+', '_', options.results_label)
    else:
      filesafe_label = 'run'
    start_time = datetime.datetime.utcnow().strftime('%Y%m%dT%H%M%SZ')
    options.intermediate_dir = os.path.join(
        options.output_dir, 'artifacts', '%s_%s' % (filesafe_label, start_time))

  if options.upload_results:
    options.upload_bucket = cloud_storage.BUCKET_ALIASES.get(
        options.upload_bucket, options.upload_bucket)
  else:
    options.upload_bucket = None

  if not options.output_formats:
    options.output_formats = ['html']
  else:
    options.output_formats = sorted(set(options.output_formats))
  if 'none' in options.output_formats:
    options.output_formats.remove('none')

  if options.fetch_device_data:
    if not options.fetch_data_platform:
      raise argparse.ArgumentError(options.fetch_data_platform,
                                   ('--fetch-device-data-platform must be set '
                                    'with --fetch-device-data'))
    if not options.device_data_path:
      raise argparse.ArgumentError(options.device_data_path,
                                   ('--fetch-data-path-device must be set '
                                    'with --fetch-device-data'))


def _CreateTopLevelParser(standalone):
  """Create top level parser, and group for result options."""
  if standalone:
    parser = argparse.ArgumentParser(
        description='Standalone command line interface to results_processor.')
    # In standalone mode, both the parser and group are the same thing.
    return parser, parser
  parser = argparse.ArgumentParser(add_help=False)
  group = parser.add_argument_group(title='Result processor options')
  return parser, group


def _DefaultOutputDir():
  """Default output directory.

  Points to the directory of the benchmark runner script, if found, or the
  current working directory otherwise.
  """
  main_module = sys.modules['__main__']
  if hasattr(main_module, '__file__'):
    return os.path.realpath(os.path.dirname(main_module.__file__))
  return os.getcwd()


def Sentences(*args):
  return ' '.join(s for s in args if s)
